package com.dai.provider3001.controller;

import com.dai.com_api.entity.Dept;
import com.dai.provider3001.impl.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;
    //提供服务发现的 - 一定要引入 org.springframework.cloud 包下的 DiscoveryClient
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/dept/add")
    public boolean add(@RequestBody Dept dept){
        return deptService.add(dept);
    }

    @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET)
    public Dept get(@PathVariable("id") int id){
        return deptService.findById(id);
    }

    @RequestMapping("/dept/list")
    public List<Dept> list(){
        return deptService.findAll();
    }

    @RequestMapping("/get/service")
    public Object getService(){
        //得到所有微服务 - 称为 “服务发现”  配合在本启动类的@EnableDiscoveryClient 使用
        List<String> list = discoveryClient.getServices();
        System.out.println(list);

        //根据微服务名称(spring.application.name配置的)来得到具体的某个微服务
        List<ServiceInstance> srvList = discoveryClient.getInstances("DAI-PROVIDER-3001");
        for(ServiceInstance element : srvList){
            System.out.println("ServiceId:"+element.getServiceId()+"  host:"+element.getHost()+"  port:"+element.getPort()+"  url:"+element.getUri());
        }

        return this.discoveryClient;
    }
}
